package erfgame.core.graphics.renderer.chain;

import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;


import erfgame.core.entity.Entity;
import erfgame.core.graphics.renderer.EntityRenderer;
import erfgame.core.graphics.renderer.PrototypeEntityRenderer;
import erfgame.core.world.World;

@SuppressWarnings(value="unchecked")
public class CompositeChainedRenderer 
	extends AbstractChainedRenderer 
	implements PrototypeEntityRenderer{
	
	private List<ChainedRenderer> renderers;

	public CompositeChainedRenderer( List<ChainedRenderer> renderers ) {
		this.renderers = renderers;
		for( int i=0; i<renderers.size()-1; i++ ) {
			ChainedRenderer renderer = renderers.get(i);
			ChainedRenderer child = renderers.get(i+1);
			renderer.setChild(child, false);
		}
		super.setChild(renderers.get(0), false);
	}
	
	@Override
	public EntityRenderer getChild() {
		return this.renderers.get(this.renderers.size()-1).getChild();
	}

	@Override
	public void setChild(EntityRenderer child, boolean started) {
		this.renderers.get(this.renderers.size()-1).setChild(child, started);
	}

	@Override
	public void start() {
		super.start();
		for( int i=this.renderers.size(); i>0; ) {
			i--;
			EntityRenderer renderer = renderers.get(i);
			renderer.start();
		}
	}

	@Override
	public void stop() {
		super.stop();
		for( int i=this.renderers.size(); i>0; ) {
			i--;
			EntityRenderer renderer = renderers.get(i);
			renderer.stop();
		}
	}

	public void render(Graphics g, int x, int y) {
		this.renderers.get(0).render(g, x, y);
	}

	public CompositeChainedRenderer spawn( World world, Entity entity ) {
		ArrayList<ChainedRenderer> renderers;
		renderers = new ArrayList<ChainedRenderer>( this.renderers.size() );
		for( int i=0; i<this.renderers.size(); i++ ) {
			ChainedRenderer renderer = this.renderers.get(i);
			if( renderer instanceof PrototypeEntityRenderer ) {
				renderer = (ChainedRenderer)((PrototypeEntityRenderer)renderer).spawn(world, entity);
			}
			renderers.add( renderer );
		}
		CompositeChainedRenderer result;
		result = new CompositeChainedRenderer(renderers);
		result.setType( this.getType() );
		result.setPriority( this.getPriority() );
		return result;
	}	
}
